//
//  ChivoxBus.m
//  ChivoxEngine
//
//  Created by xianchen.peng on 2018/9/27.
//  Copyright © 2018 Chivox. All rights reserved.
//

#import "ChivoxBus.h"

#define _STATE_UNREACH 0
#define _STATE_DETECTING 1
#define _STATE_REACH 2

@interface ChivoxBus() <NSURLSessionDelegate>
@property (nonatomic, assign) int _state;
@property (nonatomic, strong) NSMutableArray *_logQue;
@property (nonatomic, assign) float _tickTimer;
@property (nonatomic, assign) float _delayTimer;
@property (nonatomic, strong) NSURLSessionConfiguration *_urlConfig;
@property (nonatomic, strong) NSURLSession *_urlSession;
@end

@implementation ChivoxBus

- (id)init {
    if (self = [super init]) {
        self._logQue = [[NSMutableArray alloc] init];
        self._state = _STATE_UNREACH;
        self._tickTimer = 0;
        self._delayTimer = 0;
        self._urlConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"ChivoxLogBusConnection"];
        self._urlConfig.allowsCellularAccess = true;
        self._urlConfig.discretionary = true;
        self._urlSession = [NSURLSession sessionWithConfiguration:self._urlConfig delegate:nil delegateQueue:nil];
    }
    return self;
}

- (int)_checkConnect {
    return 0;
}

- (void)tick:(float)dt {
#if 0
    self._tickTimer += dt;
    float tickTimer = self._tickTimer;
    if (tickTimer > 5000) { // 每隔5秒tick一次
        self._tickTimer = 0;
        
        if (self._state == _STATE_DETECTING) {
            return;
        } else {
            
        }
        
        if (self._state == _STATE_REACH) {
            
        }
        
        int netState = [self _checkConnect];
        
        if (netState == 0) {
            return;
        }
        
        if (self.)
        
        if (self._state == _STATE_CONNECTED) {
            // 检查连接是否OK 如不OK 返回
            return;
        }
        if (self._state == _STATE_DELAY) {
            self._delayTimer += tickTimer;
            if (self._delayTimer > 5000) { // delay 5000ms
                self._state = _STATE_CONNECTING;
                // 连接
            }
            return;
        }
        if (self._state == _STATE_CONNECTING) {
            // 检查连接是否超时
            return;
        }
    }
    
#endif
}

- (void)postEid:(int)eid est:(int)est body:(NSDictionary *)body {
    
}



#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
}


@end
